package org.atlantis.grosbeak.depot.proxy.value;

import java.util.ArrayList;
import java.util.Collection;

import org.atlantis.grosbeak.depot.DepotException;
import org.atlantis.grosbeak.depot.DepotMaker;
import org.atlantis.grosbeak.depot.desc.ValueDesc;
import org.atlantis.grosbeak.depot.proxy.ValueProxy;
import org.atlantis.grosbeak.lang.Exceptions;

/**
 * 集合值代理。配置文件中的声明也是[xxx, xxx, xxx]和数组一样，但是看你需要获得什么样的类型的对象，如果是数组，那么 就把[xxx, xxx,
 * xxx]转换成一个数组，如果是Collection，那么就把[xxx, xxx, xxx]转换成一个Collection。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
@SuppressWarnings("unchecked")
public class CollectionValueProxy implements ValueProxy {

	private Class<? extends Collection<Object>> clazz;
	private ValueProxy[] values;

	public CollectionValueProxy(DepotMaker maker, Collection<ValueDesc> vds,
			Class<? extends Collection<Object>> clazz) {
		this.clazz = (Class<? extends Collection<Object>>) (null == clazz ? ArrayList.class
				: clazz);
		values = new ValueProxy[vds.size()];
		int i = 0;
		for (ValueDesc vd : vds) {
			values[i++] = maker.makeValue(vd);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.atlantis.grosbeak.depot.proxy.ValueProxy#get(org.atlantis.grosbeak
	 * .depot.DepotMaker)
	 */
	public Object get(DepotMaker maker) {
		try {
			Collection<Object> re = clazz.newInstance();
			for (ValueProxy vp : values)
				re.add(vp.get(maker));
			return re;
		} catch (Exception e) {
			throw Exceptions.wrapThrow(DepotException.class, e);
		}
	}
}
